<?php
// +----------------------------------------------------------------------
// | Copyright (c) 2019~2023 https://www.meoyun.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件，不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 喵云科技 【https://www.meoyun.com】
// +----------------------------------------------------------------------


namespace app\api\controller;

use app\common\service\WeChatMnpService;
use app\model\UsersModel;
use support\Redis;

class Login extends BaseApi
{

    /**
     * 微信小程序登录
     */
    public function mnpLogin()
    {
        $params = request()->post();

        // 验证参数
        $validator = validator($params, [
            'code' => 'required'
        ], [
            'code.required' => 'code不能为空'
        ]);

        if ($validator->fails()) {
            return $this->fail($validator->errors()->first());
        }

        try {
            // 通过微信小程序服务获取用户信息
            $weChatService = new WeChatMnpService();
            $wechatData = $weChatService->getMnpResByCode($params['code']);
            
            if (!$wechatData) {
                return $this->fail('微信授权失败，请重试');
            }

            // 创建或更新用户
            $user = UsersModel::createOrUpdateWechatUser($wechatData, 'wechat_mp');

            // 生成token
            $token = randomString();
            $ttl = 3600 * 24 * 7; // 七天

            Redis::setex($token, $ttl, $user->id);

            // 更新登录信息
            self::updateLoginInfo($user->id);

            return $this->success([
                'token' => $token,
                'user' => $user
            ]);
        } catch (\Exception $e) {
            return $this->fail('登录失败：' . $e->getMessage());
        }
    }


    public static function updateLoginInfo($userId)
    {
        $user = UsersModel::find($userId);
        if (!$user) {
            throw new \Exception('用户不存在');
        }

        $user->update([
            'last_login_time' => date('Y-m-d H:i:s'),
            'last_login_ip' => request()->getRealIp()
        ]);
    }
}